<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/21 01:47
 */

namespace module\chat\controller;

use module\chat\enum\RoleEnum;
use module\chat\front\searcher\CategorySearcher;
use module\chat\logic\RoleLogic;
use module\user\library\UserController;
use module\user\logic\FavoriteLogic;
use mof\annotation\InjectLogic;
use mof\ApiResponse;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\response\Json;

class Assistant extends UserController
{
    #[InjectLogic(\module\chat\model\Assistant::class)]
    protected RoleLogic $logic;

    protected RoleEnum $type = RoleEnum::ASSISTANT;

    public function read(int $id, FavoriteLogic $favLogic): Json
    {
        $detail = $this->logic->read($id)
            ->scene('detail')
            ->append(['category']);
        $collection = new Collection([$detail]);
        if ($this->auth->isLogin()) {
            $favLogic->appendStatus($this->auth->getId(), $collection);
        }
        return ApiResponse::success($collection->pop());
    }

    public function categories(CategorySearcher $searcher): Json
    {
        return ApiResponse::success(
            $searcher->params(['type' => $this->type->value], false)->select()
        );
    }

    public function index(): Json
    {
        if ($this->request->get('category_id/d') === -1) {
            $paginate = $this->logic->favorites($this->auth, $this->request);
        } else {
            $paginate = $this->logic->search($this->auth, $this->request);
        }
        return ApiResponse::success($paginate);
    }

    /**
     * 增删收藏
     * @param int $id
     * @param FavoriteLogic $logic
     * @return Json
     * @throws DataNotFoundException
     */
    public function favorite(int $id, FavoriteLogic $logic): Json
    {
        $source = $this->logic->read($id);
        if ($this->request->isPost()) {
            $logic->collect($this->auth->getId(), $source);
        } else if ($this->request->isDelete()) {
            $logic->uncollect($this->auth->getId(), $source);
        }
        return ApiResponse::success();
    }

}